# generate_polynomials.py
import numpy as np
from .normalize import normalize

"""
构建多项式特征的函数。函数名为generate_polynomials，
接受一个数据集dataset、多项式的次数polynomial_degree和一个布尔值normalize_data作为参数。
函数的作用是将输入的数据集生成对应的多项式特征
"""


def generate_polynomials(dataset, polynomial_degree, normalize_data=False):
    features_split = np.array_split(dataset, 2, axis=1)
    # 将输入的数据集按列分成两部分，分别赋值给dataset_1和dataset_2
    dataset_1 = features_split[0]
    dataset_2 = features_split[1]
    # 获取dataset_1和dataset_2的行数和列数，
    # 分别赋值给num_examples_1、num_features_1、num_examples_2和num_features_2
    (num_examples_1, num_features_1) = dataset_1.shape
    (num_examples_2, num_features_2) = dataset_2.shape
    # 判断dataset_1和dataset_2的行数是否相等，如果不相等则抛出ValueError异常
    if num_examples_1 != num_examples_2:
        raise ValueError('Can not generate polynomials for two sets with different number of rows')
    # 判断dataset_1和dataset_2的列数是否都为0，如果是则抛出ValueError异常
    if num_features_1 == 0 and num_features_2 == 0:
        raise ValueError('Can not generate polynomials for two sets with no columns')
    # 判断dataset_1和dataset_2的列数是否有一个为0，如果是则将另一个赋值给它
    if num_features_1 == 0:
        dataset_1 = dataset_2
    elif num_features_2 == 0:
        dataset_2 = dataset_1

    # 根据num_features_1和num_features_2的大小确定num_features的值，
    # 并将dataset_1和dataset_2的列数截取到num_feature
    num_features = num_features_1 if num_features_1 < num_examples_2 else num_features_2
    dataset_1 = dataset_1[:, :num_features]
    dataset_2 = dataset_2[:, :num_features]

    # 创建一个空的数组polynomials，用于存储生成的多项式特征
    polynomials = np.empty((num_examples_1, 0))

    """
    使用两层循环生成多项式特征。外层循环控制多项式的次数，内层循环控制多项式中各项的次数。
    在每次循环中，根据当前的次数计算多项式特征，并将其与polynomials进行拼接
    """
    for i in range(1, polynomial_degree + 1):
        for j in range(i + 1):
            polynomial_feature = (dataset_1 ** (i - j)) * (dataset_2 ** j)
            polynomials = np.concatenate((polynomials, polynomial_feature), axis=1)

    # 判断是否对变量polynomials进行归一化处理。如果normalize_data为True，
    if normalize_data:
        # 调用normalize函数对polynomials进行归一化处理，并返回处理后的结果
        polynomials = normalize(polynomials)[0]

    return polynomials